import { Injectable } from '@nestjs/common';
import { Repository,In, Not, ReturnDocument,Like} from 'typeorm';
import { InjectRepository} from '@nestjs/typeorm';
import { User } from '../user/entities/user.entity';
import {Menu} from '../menu/entities/menu.entity';
import { SysRoleWithMenuEntity } from '../role/entities/role.menu.entity';
import { SysUserWithRoleEntity } from '../user/entities/user.role.entity'
import { makeSalt, encryptPassword } from '../../../common/utils/crypto';
import {ResultData} from '../../../common/utils/result';
import { JwtService } from '@nestjs/jwt';


function buildTreeIterative(data) {
    const idMap = new Map();
    const tree = [];
  
    // 先创建 Map 映射
    data.forEach(item => {
      idMap.set(item.menuid, { ...item, children: [] });
    });
  
    // 构造树
    data.forEach(item => {
      const node = idMap.get(item.menuid);
      if (item.parentid == "0" || item.parentid == "" ) {
        tree.push(node); // 根节点直接放到树中
      } else {
        const parent = idMap.get(item.parentid);
        if (parent) {
          parent.children.push(node); // 添加到父节点的 children
        }
      }
    });
  
    return tree;
  }

@Injectable()
export class AuthService {
    constructor(
        @InjectRepository(User)
        private UserRepository: Repository<User>,
        private jwtService: JwtService,
        @InjectRepository(SysUserWithRoleEntity)
        private userWithRoleEntity: Repository<SysUserWithRoleEntity>,
        @InjectRepository(Menu)
        private menuRepository: Repository<Menu>,
        @InjectRepository(SysRoleWithMenuEntity)
        private roleMenuRepository: Repository<SysRoleWithMenuEntity>,

      ) {}
    
    async token(username:string,password:string){
        const user = await this.UserRepository.findOne({where:{username:username}});
        const salt = user.password_salt;
        const pwd = encryptPassword(password,salt);
        if(user){
            if(pwd === user.password){
                const token = this.jwtService.sign({
                    id:user.userid,
                    username:user.username,
                });
                user.token = token;
                const res = await this.UserRepository.update({ userid: user.userid }, user) 
                return {token:token};
            }else{
                return ResultData.fail(401,'密码错误');
            }
        }else{
            return ResultData.fail(401,'用户名错误');
        }
        //if(pwd === user.password)
        // if(user){
        //     return {token:'123'};
        // }else{
        //     return ResultData.fail(401,'用户名或密码错误');
        // }
    }

    async userInfo(token:string){
        const user = await this.UserRepository.findOne({where:{token:token}});
        if(user){
            return ResultData.ok({
                id:user.userid,
                username:user.username,
                nickname:user.nickname,
                avatar:user.avatar,
                email:user.email,
                phone:user.phone,
                status:user.status,
            });
        }else{
            return ResultData.fail(401,'用户不存在');
        }

    }

    async userMenu(token:string,name:string){
        //通过token查询用户id
        const user = await this.UserRepository.findOne({where:{token:token}});
        if(user){
            const userId = user.id.toString();
            const roleList = await this.userWithRoleEntity.find({where:{userid:userId}});
            if(roleList.length == 0){
                return ResultData.fail(401,'用户角色不存在');
            }else{
                const roleIds = roleList.map(item => item.roleid);
                const menuIdList = await this.roleMenuRepository.find({where:{roleid:In(roleIds)}});
                if(menuIdList.length == 0){
                    return ResultData.fail(401,'用户角色对应的菜单不存在');
                }
                const menuIds = menuIdList.map(item => item.menuid);
                console.log(name,'name')
                let _name = ""
                if(name&&name!='undefined'){
                    _name = name;
                }
                
                const menuList = await this.menuRepository.find({where:{id:In(menuIds),name:Like(`%${_name}%`)}});
                console.log(menuList,'menuList')
                const data = buildTreeIterative(menuList);
                return ResultData.ok(data);
            }
        }else{
            return ResultData.fail(401,'用户不存在');
        }
        
        //通过用户id查询角色
        


    }

}